<template>
  <view class="login-container">
    <view class="login-header">
      <text class="app-name">李岩广告门市</text>
      <text class="app-desc">看广告免费兑换打印</text>
    </view>
    
    <view class="login-content">
      <!-- 微信登录 -->
      <!-- #ifdef MP-WEIXIN -->
      <button class="login-btn wechat-btn" @click="wechatLogin">
        <text class="btn-icon">🔐</text>
        <text class="btn-text">微信快捷登录</text>
      </button>
      
      <!-- 开发环境快速登录 -->
      <button v-if="isDevelopment" class="login-btn phone-btn" @click="quickLogin">
        <text class="btn-icon">⚡</text>
        <text class="btn-text">开发环境快速登录</text>
      </button>
      <!-- #endif -->
      
      <!-- H5手机号登录 -->
      <!-- #ifdef H5 -->
      <H5Login @login-success="onLoginSuccess" />
      <!-- #endif -->
    </view>
  </view>
</template>

<script>
// #ifdef H5
import H5Login from '@/components/H5Login.vue'
// #endif

export default {
  name: 'LoginPage',
  components: {
    // #ifdef H5
    H5Login
    // #endif
  },
  data() {
    return {
      phone: '',
      smsCode: '',
      countdown: 0,
      canSendCode: true,
      isDevelopment: process.env.NODE_ENV === 'development'
    }
  },
  
  computed: {
    codeButtonText() {
      return this.countdown > 0 ? `${this.countdown}s` : '发送验证码'
    }
  },
  
  methods: {
    // 微信登录
    async wechatLogin() {
      try {
        // #ifdef MP-WEIXIN
        uni.showLoading({ title: '登录中...' })
        
        // 导入微信工具函数
        const { wechatLoginFlow, formatWechatUserInfo } = require('@/utils/wechat')
        
        // 使用简化的微信登录流程（不获取用户详细信息）
        const { code, userInfo } = await wechatLoginFlow()
        
        console.log('微信登录参数:', { code, userInfo: formatWechatUserInfo(userInfo) })
        
        // 调用登录接口并等待完成
        const loginResult = await this.$store.dispatch('auth/wechatLogin', {
          code,
          userInfo: formatWechatUserInfo(userInfo)
        })
        
        console.log('微信登录结果:', loginResult)
        console.log('登录结果详细信息:', JSON.stringify(loginResult, null, 2))
        
        // 验证登录状态
        const isLoggedIn = this.$store.getters['auth/isLoggedIn']
        const token = this.$store.state.auth.token
        const userInfoFromStore = this.$store.state.auth.userInfo
        
        console.log('登录后状态检查:', {
          isLoggedIn,
          hasToken: !!token,
          hasUserInfo: !!userInfoFromStore,
          userId: userInfoFromStore?.id
        })
        
        if (!isLoggedIn || !token) {
          throw new Error('登录状态保存失败')
        }
        
        uni.hideLoading()
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })
        
        // 登录成功，跳转到首页
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }, 1500)
        // #endif
      } catch (error) {
        uni.hideLoading()
        console.error('微信登录失败:', error)
        
        // 提供友好的错误提示
        let errorMessage = '微信登录失败'
        if (error.message.includes('获取登录凭证失败')) {
          errorMessage = '网络连接异常，请重试'
        } else if (error.message.includes('当前环境不支持')) {
          errorMessage = '当前环境不支持微信登录'
        } else if (error.message.includes('登录状态保存失败')) {
          errorMessage = '登录状态保存失败，请重试'
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 发送验证码
    async sendCode() {
      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return
      }
      
      try {
        await this.$store.dispatch('auth/sendSmsCode', this.phone)
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        
        this.startCountdown()
      } catch (error) {
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      }
    },
    
    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      this.canSendCode = false
      
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.canSendCode = true
        }
      }, 1000)
    },
    
    // 开发环境快速登录
    async quickLogin() {
      try {
        uni.showLoading({ title: '登录中...' })
        
        // 导入请求工具
        const request = require('@/utils/request').default
        
        // 使用测试账号直接登录
        const response = await request.post('/api/auth/login', {
          phone: '13800138000',
          password: '123456'
        })
        
        if (response.success) {
          // 设置认证信息到store
          this.$store.commit('auth/SET_TOKEN', {
            accessToken: response.data.token,
            refreshToken: response.data.token
          })
          
          this.$store.commit('auth/SET_USER_INFO', response.data.user)
          
          uni.hideLoading()
          
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          
          // 跳转到首页
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index'
            })
          }, 1500)
        }
      } catch (error) {
        uni.hideLoading()
        console.error('快速登录失败:', error)
        uni.showToast({
          title: error.message || '登录失败',
          icon: 'none'
        })
      }
    },
    
    // 登录成功回调
    onLoginSuccess() {
      console.log('登录成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.login-header {
  text-align: center;
  margin-bottom: 100rpx;
  
  .app-name {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: white;
    margin-bottom: 20rpx;
  }
  
  .app-desc {
    display: block;
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.login-content {
  width: 100%;
  max-width: 600rpx;
}

.login-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
  border: none;
  font-size: 32rpx;
  
  &.wechat-btn {
    background-color: #07c160;
    color: white;
  }
  
  &.phone-btn {
    background-color: #007aff;
    color: white;
  }
  
  .btn-icon {
    margin-right: 16rpx;
    font-size: 36rpx;
  }
  
  .btn-text {
    font-weight: 500;
  }
}

.phone-login {
  .phone-input, .code-input {
    width: 100%;
    height: 88rpx;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 44rpx;
    padding: 0 30rpx;
    margin-bottom: 30rpx;
    font-size: 32rpx;
    border: none;
    box-sizing: border-box;
  }
  
  .code-row {
    display: flex;
    align-items: center;
    gap: 20rpx;
    margin-bottom: 30rpx;
    
    .code-input {
      flex: 1;
      margin-bottom: 0;
    }
    
    .send-code-btn {
      width: 200rpx;
      height: 88rpx;
      background-color: rgba(255, 255, 255, 0.2);
      color: white;
      border: 2rpx solid rgba(255, 255, 255, 0.3);
      border-radius: 44rpx;
      font-size: 24rpx;
      
      &:disabled {
        opacity: 0.5;
      }
    }
  }
}
</style>